package com.ljkj.lawyer.lawyer.service;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.ljkj.lawyer.lawyer.chainmaker.AddHashCodeByUserIdParam;
import com.ljkj.lawyer.lawyer.common.CaseTypeEnum;
import com.ljkj.lawyer.lawyer.common.ContractConstant;
import com.ljkj.lawyer.lawyer.common.HashCodeTypeEnum;
import com.ljkj.lawyer.lawyer.common.MessageResult;
import com.ljkj.lawyer.lawyer.dao.LawyerCaseCodeRecordDao;
import com.ljkj.lawyer.lawyer.dao.LawyerLitigationBrieflyDao;
import com.ljkj.lawyer.lawyer.dao.LawyerLitigationCaseDao;
import com.ljkj.lawyer.lawyer.entity.LawyerCaseCodeRecordEntity;
import com.ljkj.lawyer.lawyer.entity.LawyerLitigationBrieflyEntity;
import com.ljkj.lawyer.lawyer.entity.LawyerLitigationCaseEntity;
import com.ljkj.lawyer.lawyer.ipfs.AddResult;
import com.ljkj.lawyer.lawyer.param.HttpMemberRes;
import com.ljkj.lawyer.lawyer.param.JsonParam;
import com.ljkj.lawyer.lawyer.param.litigation.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CaseService {
    @Autowired
    private HttpService httpService;
    @Autowired
    private LawyerCaseCodeRecordDao lawyerCaseCodeRecordDao;
    @Autowired
    private LawyerLitigationBrieflyDao lawyerLitigationBrieflyDao;
    @Autowired
    private LawyerLitigationCaseDao lawyerLitigationCaseDao;


    public String addCaseToIpfs(AddOrUpdateCaseParam addParam, Integer memberId) {
        IPFSCaseParam ipfsParam = new IPFSCaseParam();
        BeanUtils.copyProperties(addParam, ipfsParam);
        HttpMemberRes httpMemberRes = httpService.getMember(memberId);
        if (null != httpMemberRes) {
            ipfsParam.setAvatar(httpMemberRes.getAvatar());
            ipfsParam.setUsername(httpMemberRes.getUsername());
            ipfsParam.setPhone(httpMemberRes.getMobilePhone());
        }
        ipfsParam.setCreateTime(DateUtil.formatDateTime(new Date()));
        AddResult addResult = httpService.addString(JSON.toJSONString(ipfsParam));
        return addResult.getHash();
    }

    public String addCaseToIpfsForBriefly(LawyerLitigationCaseEntity lawyerLitigationCaseEntity, List<LawyerLitigationBrieflyEntity> brieflyEntityList) {
        IPFSCaseParam ipfsParam = new IPFSCaseParam();
        List<BrieflyParam> brieflyParamList = new ArrayList<>();
        BeanUtils.copyProperties(lawyerLitigationCaseEntity, ipfsParam);
        HttpMemberRes httpMemberRes = httpService.getMember(lawyerLitigationCaseEntity.getMemberId());
        if (null != httpMemberRes) {
            ipfsParam.setAvatar(httpMemberRes.getAvatar());
            ipfsParam.setUsername(httpMemberRes.getUsername());
            ipfsParam.setPhone(httpMemberRes.getMobilePhone());
        }
        if (!CollectionUtils.isEmpty(brieflyEntityList)) {
            brieflyEntityList.forEach(p -> {
                BrieflyParam brieflyParam = new BrieflyParam();
                BeanUtils.copyProperties(p, brieflyParam);
                brieflyParamList.add(brieflyParam);
            });
        }
        ipfsParam.setBrieflyList(brieflyParamList);
        ipfsParam.setCreateTime(DateUtil.formatDateTime(new Date()));
        AddResult addResult = httpService.addString(JSON.toJSONString(ipfsParam));
        return addResult.getHash();
    }


    public MessageResult getNonligitigionsCaseById(Integer id) {
        NoCaseDetailRes noCaseDetailRes = new NoCaseDetailRes();
        LawyerLitigationCaseEntity lawyerLitigationCaseEntity = lawyerLitigationCaseDao.findById(id).get();
        if (null != lawyerLitigationCaseEntity) {
            BeanUtils.copyProperties(lawyerLitigationCaseEntity, noCaseDetailRes);
            HttpMemberRes httpMemberRes = httpService.getMember(lawyerLitigationCaseEntity.getMemberId());
            if (null != httpMemberRes) {
                noCaseDetailRes.setAvatar(httpMemberRes.getAvatar());
                noCaseDetailRes.setUsername(httpMemberRes.getUsername());
            }
        }
        List<LawyerCaseCodeRecordEntity> lawyerCaseCodeRecordEntityList =  lawyerCaseCodeRecordDao.findByCaseId(id);
        if(!CollectionUtils.isEmpty(lawyerCaseCodeRecordEntityList)){
            LawyerCaseCodeRecordEntity lawyerCaseCodeRecordEntity = lawyerCaseCodeRecordEntityList.get(lawyerCaseCodeRecordEntityList.size()-1);
            noCaseDetailRes.setTxId(lawyerCaseCodeRecordEntity.getTxId());
            noCaseDetailRes.setHashCode(lawyerCaseCodeRecordEntity.getHashCode().substring(26,lawyerCaseCodeRecordEntity.getHashCode().length()-2));
        }
        MessageResult messageResult = MessageResult.success();
        messageResult.setData(noCaseDetailRes);
        return messageResult;
    }

    public MessageResult addOrUpdateLigationCase(AddOrUpdateCaseParam addParam) {
        //更新的话就把原先目前的设置为过去式新插入一条
        if (addParam.getId() != null) {
            LawyerLitigationCaseEntity verifyEntity = lawyerLitigationCaseDao.verifyId(addParam.getId());
            if (verifyEntity == null) {
                return MessageResult.error("该案件不存在");
            }
            lawyerLitigationCaseDao.updateAllCaseById(addParam.getId());
        }
        //新插入设置
        addParam.setId(null);
        LawyerLitigationCaseEntity lawyerLitigationCaseEntity = new LawyerLitigationCaseEntity();
        BeanUtils.copyProperties(addParam, lawyerLitigationCaseEntity);
        lawyerLitigationCaseEntity.setCreateTime(LocalDateTime.now());
        lawyerLitigationCaseEntity.setUpdateTime(LocalDateTime.now());
        lawyerLitigationCaseEntity.setIsLast(1);
        lawyerLitigationCaseEntity = lawyerLitigationCaseDao.save(lawyerLitigationCaseEntity);//保存最新的诉讼案件、
        Integer litigationId = lawyerLitigationCaseEntity.getId();
        if (addParam.getCaseType() == 1 && !CollectionUtils.isEmpty(addParam.getBrieflyList())) {
            addParam.getBrieflyList().forEach(p -> {
                LawyerLitigationBrieflyEntity lawyerLitigationBrieflyEntity = new LawyerLitigationBrieflyEntity();
                BeanUtils.copyProperties(p, lawyerLitigationBrieflyEntity);
                lawyerLitigationBrieflyEntity.setLitigationId(litigationId);
                lawyerLitigationBrieflyEntity.setCreateTime(LocalDateTime.now());
                lawyerLitigationBrieflyEntity.setUpdateTime(LocalDateTime.now());
                lawyerLitigationBrieflyDao.save(lawyerLitigationBrieflyEntity);
            });
        }
        String hash = this.addCaseToIpfs(addParam, addParam.getMemberId());
        //链上上传
        AddHashCodeByUserIdParam addHashCodeByUserIdParam = new AddHashCodeByUserIdParam();
        addHashCodeByUserIdParam.setContractName(ContractConstant.LAWYER);
        //加入code类型
        addHashCodeByUserIdParam.setHashCode(getLawyerJson(hash));
        addHashCodeByUserIdParam.setUserId(addParam.getMemberId());
        //添加到长安链
        MessageResult messageResult = httpService.addHashCodeToChainmaker(addHashCodeByUserIdParam);
        LawyerCaseCodeRecordEntity lawyerCaseCodeRecordEntity = new LawyerCaseCodeRecordEntity();
        lawyerCaseCodeRecordEntity.setHashCode(getLawyerCaseJson(hash));
        lawyerCaseCodeRecordEntity.setCaseId(litigationId);
        lawyerCaseCodeRecordEntity.setCreateTime(LocalDateTime.now());
        lawyerCaseCodeRecordEntity.setTxId(messageResult.getData().toString());
        lawyerCaseCodeRecordEntity.setMemberId(addParam.getMemberId());
        lawyerCaseCodeRecordEntity.setUpdateTime(LocalDateTime.now());
        lawyerCaseCodeRecordDao.save(lawyerCaseCodeRecordEntity);
        AddRes addRes =new AddRes();
        addRes.setCaseId(litigationId);
        addRes.setTxId(messageResult.getData().toString());
        addRes.setHashCode(hash);
        MessageResult result = MessageResult.success();
        result.setData(addRes);
        return result;

    }

    public MessageResult getLigationCasePageList(Integer pageNum, Integer pageSize, Integer memberId) {
        CaseListRes caseListRes = new CaseListRes();
        List<CaseRes> caseResList = new ArrayList<>();
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        Page<LawyerLitigationCaseEntity> pageResult = lawyerLitigationCaseDao.getCaseList(memberId, pageable);
        List<LawyerLitigationCaseEntity> lawyerLitigationCaseList = pageResult.getContent();
        caseListRes.setPageNum(pageNum);
        caseListRes.setTotal(pageResult.getTotalElements());
        caseListRes.setPageSize(pageSize);
        caseListRes.setPages(pageResult.getTotalPages());
        caseListRes.setMemberId(memberId);
        if (!CollectionUtils.isEmpty(lawyerLitigationCaseList)) {
            lawyerLitigationCaseList.forEach(p -> {
                CaseRes caseRes = new CaseRes();
                BeanUtils.copyProperties(p, caseRes);
                if (p.getCaseType() == 1) {
                    caseRes.setCaseType(CaseTypeEnum.LAWYER_CASE.getMsg());
                } else {
                    caseRes.setCaseType(CaseTypeEnum.LOWER_NO_CASE.getMsg());
                }
                List<LawyerCaseCodeRecordEntity> lawyerCaseCodeRecordEntityList =  lawyerCaseCodeRecordDao.findByCaseId(p.getId());
                if(!CollectionUtils.isEmpty(lawyerCaseCodeRecordEntityList)){
                    LawyerCaseCodeRecordEntity lawyerCaseCodeRecordEntity = lawyerCaseCodeRecordEntityList.get(lawyerCaseCodeRecordEntityList.size()-1);
                    caseRes.setTxId(lawyerCaseCodeRecordEntity.getTxId());
                    caseRes.setHashCode(lawyerCaseCodeRecordEntity.getHashCode().substring(26,lawyerCaseCodeRecordEntity.getHashCode().length()-2));

                }
                caseResList.add(caseRes);
            });
        }
        HttpMemberRes httpMemberRes = httpService.getMember(memberId);
        if (null != httpMemberRes) {
            caseListRes.setAvatar(httpMemberRes.getAvatar());
            caseListRes.setUsername(httpMemberRes.getUsername());
        }
        caseListRes.setCaseResList(caseResList);
        MessageResult messageResult = MessageResult.success();
        messageResult.setData(caseListRes);
        return messageResult;

    }

    public String getLawyerJson(String hashCode) {
        JsonParam jsonParam = new JsonParam();
        jsonParam.setHashCode(hashCode);
        jsonParam.setCodeType(HashCodeTypeEnum.LAWYER_CASE.getCode());
        return JSON.toJSONString(jsonParam);
    }

    public String getLawyerCaseJson(String hashCode) {
        JsonParam jsonParam = new JsonParam();
        jsonParam.setHashCode(hashCode);
        jsonParam.setCodeType(HashCodeTypeEnum.LAWYER_CASE.getCode());
        return JSON.toJSONString(jsonParam);
    }

    public MessageResult getLigationCaseById(Integer id) {
        CaseDetailRes caseDetailRes = new CaseDetailRes();
        LawyerLitigationCaseEntity lawyerLitigationCaseEntity = lawyerLitigationCaseDao.findById(id).get();
        if (null != lawyerLitigationCaseEntity) {
            BeanUtils.copyProperties(lawyerLitigationCaseEntity, caseDetailRes);
            List<BrieflyRes> brieflyResList = new ArrayList<>();
            List<LawyerLitigationBrieflyEntity> brieflyEntityList = lawyerLitigationBrieflyDao.findAllByLitigationIdOrderBySortDesc(lawyerLitigationCaseEntity.getId());
            if (!CollectionUtils.isEmpty(brieflyEntityList)) {
                brieflyEntityList.forEach(x -> {
                    BrieflyRes brieflyRes = new BrieflyRes();
                    BeanUtils.copyProperties(x, brieflyRes);
                    brieflyResList.add(brieflyRes);
                });
            }
            caseDetailRes.setBrieflyList(brieflyResList);
        }
        HttpMemberRes httpMemberRes = httpService.getMember(lawyerLitigationCaseEntity.getMemberId());
        if (null != httpMemberRes) {
            caseDetailRes.setAvatar(httpMemberRes.getAvatar());
            caseDetailRes.setUsername(httpMemberRes.getUsername());
        }
        List<LawyerCaseCodeRecordEntity> lawyerCaseCodeRecordEntityList =  lawyerCaseCodeRecordDao.findByCaseId(id);
        if(!CollectionUtils.isEmpty(lawyerCaseCodeRecordEntityList)){
            LawyerCaseCodeRecordEntity lawyerCaseCodeRecordEntity = lawyerCaseCodeRecordEntityList.get(lawyerCaseCodeRecordEntityList.size()-1);
            caseDetailRes.setTxId(lawyerCaseCodeRecordEntity.getTxId());
            caseDetailRes.setHashCode(lawyerCaseCodeRecordEntity.getHashCode().substring(26,lawyerCaseCodeRecordEntity.getHashCode().length()-2));

        }
        MessageResult messageResult = MessageResult.success();
        messageResult.setData(caseDetailRes);
        return messageResult;
    }

    public MessageResult getCaseDetail(Integer id) {
        LawyerLitigationCaseEntity lawyerLitigationCaseEntity = lawyerLitigationCaseDao.findById(id).get();
        if (null == lawyerLitigationCaseEntity) {
            return MessageResult.error("该案件不存在");
        }
        if (lawyerLitigationCaseEntity.getCaseType() == 1) {
            return this.getLigationCaseById(id);
        } else {
            return this.getNonligitigionsCaseById(id);
        }
    }

    public MessageResult addLigationCaseBriefly(AddBrieflyParam addBrieflyParam) {
        LawyerLitigationCaseEntity lawyerLitigationCaseEntity = lawyerLitigationCaseDao.verifyId(addBrieflyParam.getCaseId());
        if (null == lawyerLitigationCaseEntity) {
            return MessageResult.error("该诉讼案件不存在！");
        }
        if (1 != lawyerLitigationCaseEntity.getCaseType()) {
            return MessageResult.error("该案件不是诉讼案件！");
        }
        List<LawyerLitigationBrieflyEntity> brieflyEntityList = lawyerLitigationBrieflyDao.findAllByLitigationIdOrderBySortDesc(addBrieflyParam.getCaseId());
        Integer sort = 1;
        if (!CollectionUtils.isEmpty(brieflyEntityList)) {
            sort = brieflyEntityList.size() + 1;
        }
        //添加入库
        LawyerLitigationBrieflyEntity lawyerLitigationBrieflyEntity = new LawyerLitigationBrieflyEntity();
        lawyerLitigationBrieflyEntity.setLitigationId(addBrieflyParam.getCaseId());
        lawyerLitigationBrieflyEntity.setBriefly(addBrieflyParam.getBriefly());
        lawyerLitigationBrieflyEntity.setBrieflyName(addBrieflyParam.getBrieflyName());
        lawyerLitigationBrieflyEntity.setSort(sort);
        lawyerLitigationBrieflyEntity.setCreateTime(LocalDateTime.now());
        lawyerLitigationBrieflyEntity.setUpdateTime(LocalDateTime.now());
        lawyerLitigationBrieflyDao.save(lawyerLitigationBrieflyEntity);
        brieflyEntityList.add(lawyerLitigationBrieflyEntity);
        //更新到ipfs
        String hash = this.addCaseToIpfsForBriefly(lawyerLitigationCaseEntity, brieflyEntityList);
        AddHashCodeByUserIdParam addHashCodeByUserIdParam = new AddHashCodeByUserIdParam();
        addHashCodeByUserIdParam.setContractName(ContractConstant.LAWYER);
        //加入code类型
        addHashCodeByUserIdParam.setHashCode(getLawyerJson(hash));
        addHashCodeByUserIdParam.setUserId(lawyerLitigationCaseEntity.getMemberId());
        //添加到长安链
        MessageResult messageResult = httpService.addHashCodeToChainmaker(addHashCodeByUserIdParam);
        LawyerCaseCodeRecordEntity lawyerCaseCodeRecordEntity = new LawyerCaseCodeRecordEntity();
        lawyerCaseCodeRecordEntity.setHashCode(getLawyerCaseJson(hash));
        lawyerCaseCodeRecordEntity.setCaseId(lawyerLitigationCaseEntity.getId());
        lawyerCaseCodeRecordEntity.setCreateTime(LocalDateTime.now());
        lawyerCaseCodeRecordEntity.setTxId(messageResult.getData().toString());
        lawyerCaseCodeRecordEntity.setMemberId(lawyerLitigationCaseEntity.getMemberId());
        lawyerCaseCodeRecordEntity.setUpdateTime(LocalDateTime.now());
        lawyerCaseCodeRecordDao.save(lawyerCaseCodeRecordEntity);
        MessageResult result = MessageResult.success();
        result.setData(Boolean.TRUE);
        return result;

    }
}
